package com.example.eventbus;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {

    Button btn_normal,btn_sticky;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_normal = findViewById(R.id.btn_normal);
        textView = findViewById(R.id.textView);
        btn_sticky=findViewById(R.id.btn_sticky);
        //注册eventbus
        EventBus.getDefault().register(this);
        final MessageEvent event = new MessageEvent("to second event");
        btn_normal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().postSticky(event);
                Intent intent = new Intent(MainActivity.this, secondactivity.class);
                startActivity(intent);

            }
        });
    }

    /**
     * 处理事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void handle(MessageEvent event) {
        textView.setText(event.getMessage());
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册eventbus
        EventBus.getDefault().unregister(this);
    }
}
